import { ReactNode, useState } from 'react'
import React from 'react'

import * as auth from 'auto-provider'
import { IUser } from 'screens/project-list/search-panel'
import { http } from 'utils/http'
import { useMount } from 'utils'
import { useAsync } from 'utils/use-async'
import { FullscreenLoading, FullScreenError } from 'components/lib'
import { DevTools } from 'jira-dev-tool'
export interface IAuthForm {
  username: string
  password: string
}

const bootstrapUser = async () => {
  let user = null
  const token = auth.getToken()
  if (token) {
    const data = await http('me', { token })
    user = data.user
  }

  return user
}

const AuthContext = React.createContext<
  | {
      user: IUser | null
      login: (form: IAuthForm) => Promise<void>
      logout: () => Promise<void>
      register: (form: IAuthForm) => Promise<void>
    }
  | undefined
>(undefined)
AuthContext.displayName = 'AuthContext'

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const { data: user, error, isIdle, isError, isLoading, run, setData: setUser } = useAsync<IUser | null>()

  //登录
  const login = (form: IAuthForm) =>
    // point free
    auth.login(form).then(setUser)

  //注册
  const register = (form: IAuthForm) => auth.register(form).then(user => setUser(user))

  // 登出
  const logout = () => auth.logout().then(() => setUser(null))

  // 解决刷新页面 保持登录状态
  useMount(() => {
    run(bootstrapUser()).then(setUser)
  })
  if (isIdle || isLoading) {
    return <FullscreenLoading />
  }

  if (error) {
    return (
      <>
        <DevTools />
        <FullScreenError error={error}></FullScreenError>
      </>
    )
  }

  return <AuthContext.Provider value={{ user, login, logout, register }}>{children}</AuthContext.Provider>
}

export const useAuth = () => {
  const context = React.useContext(AuthContext)
  if (!context) throw new Error('useAuth必须在AuthProvider中使用')
  return context
}
